<template>
  <div class="inputDeep">
      <h1>农产品</h1>
    <el-button type="primary" @click="toadd">添加</el-button>
    <el-button type="primary" @click="daochu">导出压缩发送至qq邮箱</el-button>
    <el-table
        :data="tableData"
        border
        style="width: 100%">
      <el-table-column
          fixed
          prop="id"
          label="id"
          width="150">
      </el-table-column>
      <el-table-column
          prop="title"
          label="title"
          width="120">
      </el-table-column>
      <el-table-column
          prop="cropNo"
          label="cropNo"
          width="120">
      </el-table-column>
      <el-table-column
          prop="status"
          label="status"
          width="120">
        <template v-slot="s">
          <el-tag v-if="s.row.status==1">未出售</el-tag>
          <el-tag v-if="s.row.status==2">出售成功</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button @click="getByCropNo(scope.row.cropNo)" type="text" size="small">查看详情</el-button>
          <el-button @click="callCar(scope.row.cropNo)" type="text" size="small">联系运输</el-button>
          <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
          <el-button type="text" size="small">编辑</el-button>
          <el-button @click="openCondition" type="text" size="small">周期生长</el-button>
          <el-button @click="logisticsTrace()" type="text" size="small">查看物流</el-button>
          <el-button @click="getLongitudeLatitude()" type="text" size="small">获取当前经纬度</el-button>
          <el-button @click="openCondition" type="text" size="small">周期生长</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @current-change="goPage"
        :page-size="size"
        layout="total, prev, pager, next"
        :total="total">
    </el-pagination>
    <el-dialog title="详情" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="id" :label-width="formLabelWidth">
          <el-input v-model="form.id" autocomplete="off"  readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="作物名称" :label-width="formLabelWidth">
          <el-input v-model="form.zname" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="肥料名称" :label-width="formLabelWidth">
          <el-input v-model="form.fname" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="种植年度" :label-width="formLabelWidth">
          <el-input v-model="form.yeartime" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="育苗周期" :label-width="formLabelWidth">
          <el-input v-model="form.growcycle" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="施肥周期" :label-width="formLabelWidth">
          <el-input v-model="form.fcycle" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="省市县" :label-width="formLabelWidth">
          <el-input v-model="form.shid" autocomplete="off" readonly="readonly"></el-input>
          <el-input v-model="form.sid" autocomplete="off" readonly="readonly"></el-input>
          <el-input v-model="form.xid" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="作物类型" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="种植类型" :label-width="formLabelWidth">
          <el-input v-model="form.zzid" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="灌溉周期" :label-width="formLabelWidth">
          <el-input v-model="form.lcycle" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="除草周期" :label-width="formLabelWidth">
          <el-input v-model="form.wcycle" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="用户id" :label-width="formLabelWidth">
          <el-input v-model="form.userId" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="作物编号" :label-width="formLabelWidth">
          <el-input v-model="form.cropNo" autocomplete="off" readonly="readonly"></el-input>
        </el-form-item>

      </el-form>
    </el-dialog>

    <el-dialog title="记录作物" :visible.sync="dialogFormVisible3">
      <el-form :model="form3">
        <el-form-item label="作物名称" :label-width="formLabelWidth">
          <el-input v-model="form3.zname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="肥料名称" :label-width="formLabelWidth">
          <el-input v-model="form3.fname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="种植年度" :label-width="formLabelWidth">
          <el-input v-model="form3.year" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="育苗周期" :label-width="formLabelWidth">
          <el-input v-model="form3.scycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="施肥周期" :label-width="formLabelWidth">
          <el-input v-model="form3.fcycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-select v-model="form3.shid" placeholder="省" @change="getsid">
            <el-option v-for="sh in sheng" :label="sh.name" :value="sh.id" :key="sh.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-select v-model="form3.sid" placeholder="市" @change="getxid">
            <el-option v-for="s in shi" :label="s.name" :value="s.id" :key="s.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-select v-model="form3.xid" placeholder="县">
            <el-option v-for="x in xian" :label="x.name" :value="x.id" :key="x.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog title="收货地址" :visible.sync="dialogFormVisible1">
      <el-form :model="form1">
        <el-form-item label="温度" :label-width="formLabelWidth1">
          <el-input v-model="form1.temperature" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="水分" :label-width="formLabelWidth1">
          <el-input v-model="form1.water" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth1">
          <el-input v-model="form1.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="生长情况" :label-width="formLabelWidth1">
          <el-input v-model="form1.growthCondition" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="光照情况" :label-width="formLabelWidth1">
          <el-input v-model="form1.lightCondition" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="农物作业" :label-width="formLabelWidth1">
            <el-checkbox v-model="form1.wids" v-for="m in wordData" :label="m.id" :key="m.id">{{m.name}}</el-checkbox>
        </el-form-item>
        <el-form-item label="大文件上传" :label-width="formLabelWidth1">
          <uploader :options="options" class="uploader-example">
            <uploader-unsupport></uploader-unsupport>
            <uploader-drop>
              <p>Drop files here to upload or</p>
              <uploader-btn>select files</uploader-btn>
              <uploader-btn :attrs="attrs">select images</uploader-btn>
              <uploader-btn :directory="true">select folder</uploader-btn>
            </uploader-drop>
            <uploader-list></uploader-list>
          </uploader>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form3.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作物类型" :label-width="formLabelWidth">
          <el-select v-model="form3.zwid" placeholder="作物类型">
            <el-option v-for="z in zw" :label="z.name" :value="z.id" :key="z.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="种植方式" :label-width="formLabelWidth">
          <el-select v-model="form3.zzid" placeholder="种植方式">
            <el-option v-for="zz in zz" :label="zz.name" :value="zz.id" :key="zz.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否套袋" :label-width="formLabelWidth">
          <el-select v-model="form3.bagging" placeholder="是否套袋">
            <el-option label="套袋" value="套袋"></el-option>
            <el-option label="不套袋" value="不套袋"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="灌溉周期" :label-width="formLabelWidth">
          <el-input v-model="form3.lcycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="除草周期" :label-width="formLabelWidth">
          <el-input v-model="form3.wcycle" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="联系司机" :visible.sync="dialogFormVisible2">
      <el-form :model="form2">

        <el-form-item label="选择司机" :label-width="formLabelWidth">
          <el-select v-model="form2.sendName" placeholder="请选择" @change="selectProductType">
            <el-option v-for="c in car" :key="c" :label="c.realName" :value="c.realName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="原料厂商" :label-width="formLabelWidth">
          <el-select v-model="form2.goodsFrom" placeholder="请选择" @change="selectProductType">
            <el-option v-for="d in dept" :key="d" :label="d.name" :value="d.name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="addCar">确 定</el-button>
      </div>
    </el-dialog>
    <el-drawer size="80%" :visible.sync="playTrackView" :show-close="false" :with-header="false">
      <el-divider content-position="left">物流追踪</el-divider>
      <el-container style="height: 600px; border: 1px solid #eee">
        <el-main>
          <div id="container" class="map-page" style="height: 100%"></div>
        </el-main>
      </el-container>
      <div id="container" class="map"></div>
    </el-drawer>
  </div>
</template>

<script src="https://webapi.amap.com/loader.js"></script>
<script type="text/javascript">
import * as AMapLoader from "@amap/amap-jsapi-loader";
AMapLoader.load({
  key: "408f7cc153cb5ec7684b18322d464ea2", //申请好的Web端开发者key，调用 load 时必填
  version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
})
    .then((AMap) => {
      //JS API 加载完成后获取AMap对象
    })
    .catch((e) => {
      console.error(e); //加载错误提示
    });
</script>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<!-- 获取地理位置 这个key是申请的 感谢-->
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.3&key=408f7cc153cb5ec7684b18322d464ea2"></script>

<script>

import {API} from "@/api/config";

export default {
  name: "CropView",

  data() {
    return {
      dialogFormVisible2:false,
      dialogFormVisible3:false,
      form2:{
        notifier:'',
        goodsNo:''
      },
      car:[],
      dept:[],
      form3:{
        shid:'',
        sid:'',
        xid:'',
      },
      sheng:[],
      shi:[],
      xian:[],
      zw:[],
      zz:[],
      playTrackView: false,
      map:null,
      tableData: [],
      size: 3,
      current: 1,
      total: 0,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      dialogFormVisible1: false,
      formLabelWidth1:'120px',
      form1: {wids: []},
      form:{},
      wordData: [],
      options: {
        target: API + '/files/fileUpload',
        testChunks: false
      },
      attrs: {
        accept: 'image/*'
      },
      jing1:116.397477,
      wei1:39.908692,
    }
  },async mounted() {
    this.wsIsRun = true
    this.wsInit();
  }, methods: {
    sendDataToServer() {
      if (this.webSocket.readyState === 1) {
        this.webSocket.send('接受成功')
      } else {
        throw Error('服务未连接')
      }
    },
    wsInit(){
      const wsuri = 'ws://localhost:9988/websocket/pushone'
      this.ws = wsuri
      if (!this.wsIsRun) return
      // 销毁ws
      this.wsDestroy()
      // 初始化ws
      this.webSocket = new WebSocket(this.ws)
      // ws连接建立时触发
      this.webSocket.addEventListener('open', this.wsOpenHanler)
      // ws服务端给客户端推送消息
      this.webSocket.addEventListener('message', this.wsMessageHanler)
      // ws通信发生错误时触发
      this.webSocket.addEventListener('error', this.wsErrorHanler)
      // ws关闭时触发
      this.webSocket.addEventListener('close', this.wsCloseHanler)

      // 检查ws连接状态,readyState值为0表示尚未连接，1表示建立连接，2正在关闭连接，3已经关闭或无法打开
      clearInterval(this.wsTimer)
      this.wsTimer = setInterval(() => {
        if (this.webSocket.readyState === 1) {
          clearInterval(this.wsTimer)
        } else {
          console.log('ws建立连接失败')
          this.wsInit()
        }
      }, 3000)
    },
    wsOpenHanler() {
      console.log('ws建立连接成功')
    },
    wsMessageHanler(e) {
      console.log('wsMessageHanler')
      console.log(e.data)
      this.jingwei = e.data;

      if(e.data!="来自后台的反馈：连接成功"){
        let coord = e.data.split(",");
        let x = parseFloat(coord[0]);
        let y = parseFloat(coord[1]);

        this.jing1 = x;
        this.wei1 = y;
        this.initAMap();
      }

      // this.map.setCenter([x,y]);
      //this.map.setCenter([x,y]);

      // const redata = JSON.parse(e.data)
      // console.log(redata)
    },
    /**
     * ws通信发生错误
     */
    wsErrorHanler(event) {
      console.log(event, '通信发生错误')
      this.wsInit()
    },
    /**
     * ws关闭
     */
    wsCloseHanler(event) {
      console.log(event, 'ws关闭')
      this.wsInit()
    },
    /**
     * 销毁ws
     */
    wsDestroy() {
      if (this.webSocket !== null) {
        // this.webSocket.removeEventListener('open', this.wsOpenHanler)
        // this.webSocket.removeEventListener('message', this.wsMessageHanler)
        // this.webSocket.removeEventListener('error', this.wsErrorHanler)
        // this.webSocket.removeEventListener('close', this.wsCloseHanler)
        // this.webSocket.close()
        this.webSocket = null
        clearInterval(this.wsTimer)
      }
    },
    initAMap() {
      this.centerMarker = null;
      this.$nextTick(() => {
        this.playTrackView = true;
        const lineArr = [
          [this.jing1, this.wei1],
        ];
        //创建地图
        var map = new AMap.Map('container', {
          resizeEnable: true,
          center: [this.jing1, this.wei1],
          zoom: 9
        });
        //标记车辆
        var marker = new AMap.Marker({
          position: [this.jing1, this.wei1],
          icon: 'https://webapi.amap.com/images/car.png',
          //坐标偏移
          offset: new AMap.Pixel(-26, -13),
          autoRotation: true,
          angle: -90,
          map: map
        });
        // 绘制轨迹路线
        var polyline = new AMap.Polyline({
          map: this.map,
          //这里替换自己的坐标数据
          path: lineArr,
          borderWeight: 2, // 线条宽度，默认为 1
          strokeColor: 'red', // 线条颜色
          lineJoin: 'round' // 折线拐点连接处样式
        });
        map.add(polyline);

        //调用方法开启动画
        marker.moveAlong(lineArr, 30000);
      })
    },
    daochu(){
      this.axios.post("/crop/sc").then(()=>{
        this.$message.success("导出成功");
      })
    },
    toadd(){
      this.$router.push("/addpro");
    },
    getByCropNo(cropNo){
      this.axios.post("/crop/peaList?cropNo="+cropNo).then(res=>{
        this.form = res.data.data;
        this.dialogFormVisible = true;
      })
    },
    goPage(page){
      this.current = page;
      this.list();
    },
    list(){
      this.axios.post("/crop/cropList?current="+this.current+"&size="+this.size).then(res=>{
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
      })
    },
      add() {
        let uid = localStorage.getItem("uid");
        this.axios.post("/grow/add", this.form1, {params: {uid: uid}}).then(r => {
          if (r.data.code == 200) {
            this.$message.success("添加成功");
            this.dialogFormVisible = false;
            this.list();
          } else {
            this.$message.error("添加失败");
          }
        })
      }, openCondition() {
        this.dialogFormVisible1 = true;
      },
      getworkData() {
        this.axios.post("/cropWork/list").then(r => {
          this.wordData = r.data.data;
        })
      },
      getLongitudeLatitude() {
        //如果该对象存在，那么地理位置服务可用。
        if ('geolocation' in navigator) {
          /* 地理位置服务可用 */
          var options = {
            enableHighAccuracy: true, //布尔值，表示系统是否使用最高精度来表示结果，注意，这会导致较慢的响应时间或者增加电量消耗（比如对于支持gps的移动设备来说）。如果值为false ，设备会通过更快响应以及/或者使用更少的电量等方法来尽可能的节约资源。默认值fasle
            timeout: 5000, //它表明的是设备必须在多长时间（单位毫秒）内返回一个位置。默认直到获取到位置才会返回值。
            maximumAge: 0 //表明可以返回多长时间（即最长年龄，单位毫秒）内的可获取的缓存位置。如果设置为 0, 说明设备不能使用一个缓存位置，而且必须去获取一个真实的当前位置。默认0
          }

          // eslint-disable-next-line no-inner-declarations
          function success(position) {
            //position.coords (只读) 返回一个定义了当前位置的Coordinates对象。
            //position.timestamp (只读) 返回一个时间戳DOMTimeStamp， 这个时间戳表示获取到的位置的时间。
            var lat = position.coords.latitude //当前位置的纬度
            var lng = position.coords.longitude //当前位置精度
            console.log(lat)
            console.log(lng)
          }

          // eslint-disable-next-line no-inner-declarations
          function error(err) {
            var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时']
            console.log(errorType[err.code - 1])
          }

          navigator.geolocation.getCurrentPosition(success, error, options)
        } else {
          /* 地理位置服务不可用 */
          console.log('无法获取您的位置，请检查定位是否开启或刷新重试')
        }
      },
      logisticsTrace() {
        this.playTrackView = true;
        this.initAMap();
      },
      selectProductType(data) {
        alert(data);
      },
      addCar() {
        this.form2.notifier = localStorage.getItem("username");
        this.axios.post("/crop/addCar", this.form2).then(r => {
          if (r.data.code == 200) {
            this.$message.success("已通知运输");
            this.dialogFormVisible2 = false;
            this.list();
          } else {
            this.$message.error(r.data.msg);
          }
        })
      },
      callCar(r) {
        this.dialogFormVisible2 = true;
        this.form2.goodsNo = r;
        this.cList();
        this.dList();
      },
      cList() {
        this.axios.post("/crop/cList").then(r => {
          this.car = r.data.data;
        })
      },
      dList() {
        this.axios.post("/crop/dList").then(r => {
          this.dept = r.data.data;
        })
      },
      getsid() {
        console.log(this.form3.shid);
        this.axios.post("/crop/getProvince?pid=" + this.form3.shid).then(res => {
          this.shi = res.data.data;
          this.form3.sid = '';
          this.form3.xid = '';
        })
      },
      getxid() {
        console.log(this.form3.sid)
        this.axios.post("/crop/getProvince?pid=" + this.form3.sid).then(res => {
          this.xian = res.data.data;
        })
      },
      gettyee(){
        this.axios.post("/crop/getType?type=1").then(res=>{
          this.zw=res.data.data;
        })

      },
      getType(){
        this.axios.post("/crop/getType?type=2").then(res=>{
          this.zz=res.data.data;
        })
      },
      getProvin(){
        this.axios.post("/crop/getProvince?pid=0").then(res=>{
          this.sheng=res.data.data;
        });
      }
    }, created() {
    this.list();
    this.gettyee();
    this.getProvin();
    this.getType();
    this.getworkData();
  }

}
</script>
<style scoped>
.uploader-example {
  width: 500px;
  padding: 15px;
  margin: 40px auto 0;
  font-size: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .4);
}
.uploader-example .uploader-btn {
  margin-right: 4px;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
}


<style scoped>
/* 利用穿透，设置input边框隐藏 */
.inputDeep>>>.el-input__inner {
  border: 0;
}
/* 如果你的 el-input type 设置成textarea ，就要用这个了 */
.inputDeep>>>.el-textarea__inner {
  border: 0;
  resize: none;/* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}
#container {
  width: 100%;
  height: 800px;
}
.map {
  width: 100%;
  height: 500px;
}
</style>
